package al.xc.wxsession.controller;

import al.xc.common.exception.ResultCodeDefine;
import al.xc.common.exception.SelfBaseException;
import al.xc.data.dto.wechat.SendSubscribeBean;
import al.xc.service.IWechatAuthorService;
import al.xc.springboot.aop.ParamValidate;
import al.xc.thirdparty.wechat.authorization.IWechatConfig;
import al.xc.thirdparty.wechat.authorization.WechatUtil;
import al.xc.wxsession.controller.base.BaseController;
import al.xc.wxsession.data.ResultVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import al.xc.data.model.wechat.GlobalSessionInfo;

import javax.validation.Valid;

@Slf4j
@RestController
@Api("微信相关接口")
@RequestMapping("/wechat")
public class WechatController extends BaseController {

    @Autowired
    private IWechatAuthorService authorService;
    @Autowired
    private IWechatConfig config;

    @ApiOperation(value = "发送订阅消息", notes = "通知微信小程序用户")
    @ParamValidate(author = 0)
    @PostMapping("sendsubscribe")
    public ResultVo<Integer> sendSubscribe(@RequestBody @Valid SendSubscribeBean request, BindingResult result) throws Exception {
        GlobalSessionInfo sessionInfo =  authorService.find(request.getAppId());
        if (null == sessionInfo) {
            throw new SelfBaseException(ResultCodeDefine.EXCEPTION, "为找到对应APP的授权信息");
        }
        WechatUtil util = new WechatUtil(config, request.getAppId());
        util.sendSubscribe(sessionInfo.getSessionKey(), request.getOpenId(), request.getTemplateId(), request.getPage(), request.getData());
        return successResult(1);
    }
}
